package com.ndkj.blog.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ndkj.blog.pojo.bo.SettingModelBO;
import com.ndkj.blog.utils.Base64Utils;
import com.ndkj.blog.utils.GetToken;
import com.ndkj.blog.utils.GsonUtils;
import com.ndkj.blog.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @program: Blog
 * @description: BaiduAIFace
 * @author: liuyong
 * @create: 2021-09-23 17:24
 */
@Component
@Slf4j
public class BaiduAIFace {

    @Autowired
    private GetToken getToken;

    /**
     * 人脸注册
     *
     * @param settingModelBO
     * @return java.util.Map
     */
    public Map FaceRegistration(SettingModelBO settingModelBO) throws IOException {
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add";
        Map resultmap = FaceAddAndUpdate(settingModelBO, url);
        return resultmap;
    }

    /**
     * 人脸更新
     *
     * @param settingModelBO 参数设置
     * @return 返回信息map
     * @throws IOException
     */
    public Map FaceUpdate(SettingModelBO settingModelBO) throws IOException {
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/update";
        Map resultmap = FaceAddAndUpdate(settingModelBO, url);
        return resultmap;
    }

    private Map FaceAddAndUpdate(SettingModelBO facaddseting, String url) throws IOException {
        byte[] bytes = Files.readAllBytes(Paths.get(facaddseting.getImgpath()));
        String imagebase64 = Base64Utils.encode(bytes);
        Map<String, Object> map = new HashMap<>();
        try {
            map.put("image", imagebase64);
            map.put("group_id", facaddseting.getGroupID());
            map.put("user_id", facaddseting.getUserID());
            map.put("liveness_control", facaddseting.getLiveness_Control());
            map.put("image_type", facaddseting.getImage_Type());
            map.put("quality_control", facaddseting.getQuality_Control());
            String param = GsonUtils.toJson(map);
            String result = HttpUtils.post(url, getToken.getAuth(), "application/json", param);
            Map resultmap = GsonUtils.fromJson(result, Map.class);
            return resultmap;
        } catch (Exception e) {
            log.error("脸部信息添加失败");
            e.printStackTrace();
        }
        return new HashMap();
    }

    /**
     * 查询这个人的面部信息
     *
     * @param settingModelBO
     * @return map
     */
    public Map FindPersonFaceList(SettingModelBO settingModelBO) {
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/face/getlist";
        Map<String, Object> map = new HashMap<>();
        if (!map.isEmpty()) {
            map.clear();
        }
        map.put("group_id", settingModelBO.getGroupID());
        map.put("user_id", settingModelBO.getUserID());
        String param = GsonUtils.toJson(map);
        try {
            String result = HttpUtils.post(url, getToken.getAuth(), "application/json", param);
            return GsonUtils.fromJson(result, Map.class);
        } catch (Exception e) {

            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询本组的面部信息
     *
     * @param settingModelBO
     * @return
     */
    public Map FindGroupList(SettingModelBO settingModelBO) {
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/group/getusers";
        Map<String, Object> map = new HashMap<>();
        map.put("group_id", settingModelBO.getGroupID());
        String param = GsonUtils.toJson(map);
        try {
            String result = HttpUtils.post(url, getToken.getAuth(), "application/json", param);
            Map resultmap = GsonUtils.fromJson(result, Map.class);
            return resultmap;

        } catch (Exception e) {
            log.error("未查询到人脸信息");
            e.printStackTrace();
        }
        return null;
    }

    public Map DelPersonFace(SettingModelBO settingModelBO) {
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/face/delete";
        Map map = FindPersonFaceList(settingModelBO);
        Object result = map.get("result");
        String s = GsonUtils.toJson(result);
        JSONObject jsonObject = JSONObject.parseObject(s);
        String token = jsonObject.getString("face_list");
        String substring = token.substring(2, token.length() - 2);
        String[] split = substring.split("\"");
        token = split[7];
        map.put("group_id", settingModelBO.getGroupID());
        map.put("user_id", settingModelBO.getUserID());
        map.put("face_token", token);
        String param = GsonUtils.toJson(map);
        try {
            String result2 = HttpUtils.post(url, token, "application/json", param);
            Map resultmap = GsonUtils.fromJson(result2, Map.class);
            return resultmap;
        } catch (Exception e) {
            log.error("人脸数据删除失败");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 人脸查找
     *
     * @return
     */
    public Map faceSearch(SettingModelBO setingmodel) throws IOException {
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/search";
//        byte[] bytes = Files.readAllBytes(Paths.get(setingmodel.getImgpath()));
//        String imagebase64 = Base64Util.encode(bytes);
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("image", setingmodel.getImgpath());
            map.put("liveness_control", setingmodel.getLiveness_Control());
            map.put("group_id_list", setingmodel.getGroupID());
            map.put("image_type", setingmodel.getImage_Type());
            map.put("quality_control", setingmodel.getQuality_Control());
            String param = GsonUtils.toJson(map);
            String result = HttpUtils.post(url, getToken.getAuth(), "application/json", param);
            if (StringUtils.isNotBlank(result)) {
                System.out.println("get the search face response:" + result.substring(0, result.length() > 150 ? 150 : result.length()) + "...");
            }
            Map<String, Object> resultmaps = GsonUtils.fromJson(result, Map.class);
            if (!resultmaps.get("error_code").toString().equals("222202.0")) {
                String resultlist = resultmaps.get("result").toString();
                String substring = resultlist.substring(1, resultlist.length() - 1);
                String regEx = "[\n`~!@#$%^&*()+|{}':;'\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。， 、？]";
                String aa = "";
                Pattern p = Pattern.compile(regEx);
                //这里把想要替换的字符串传进来
                Matcher m = p.matcher(substring);
                String newString = m.replaceAll(aa).trim();
                String[] split = newString.split(",");
                split[1] = split[1].substring(10, split[1].length());
                String face_token = split[0].substring(11, split[0].length());
                String group_id = split[1].substring(9, split[1].length());
                String user_id = split[2].substring(8, split[2].length());
                String user_info = split[3].substring(10, split[3].length());
                String score = split[4].substring(6, split[4].length());
                resultmaps.put("face_token", face_token);
                resultmaps.put("group_id", group_id);
                resultmaps.put("user_id", user_id);
                resultmaps.put("user_info", user_info);
                resultmaps.put("score", score);
                return resultmaps;
            } else {
                log.error("Baidu face database no this data");
                return resultmaps;
            }
        } catch (Exception e) {
            log.error(" the request to {} fail", url);
            e.printStackTrace();
        }
        return null;
    }

}
